<template>
  <el-drawer
    show-close
    :before-close="handleClose"
    title="新增入库单"
    :visible="newInventoryEntry"
    size="60%"
  >
    <div style="margin: 0px 20px; height: 80vh; overflow: auto">
      <div
        class="drawer-div"
        v-if="!['2'].includes($store.state.user.userLevel)"
      >
        <span>选择仓库/门店</span>
        <el-select
          style="width: 300px"
          size="small"
          v-model="queryParams.stationId"
          placeholder="请选择仓库/门店"
          @change="changeStationList"
        >
          <el-option
            v-for="item in stationList"
            :key="item.stationId"
            :label="item.stationName"
            :value="item.stationId"
          >
          </el-option>
        </el-select>
      </div>
      <div class="drawer-data">
        <div>
          <div class="drawer-tree-input">
            <el-tree
              class="drawer-tree"
              :data="dataTree"
              :props="defaultProps"
              node-key="categoryId"
              @node-click="handleNodeClick"
              :default-expanded-keys="dataTreeId"
              v-loading="loadingTree"
            ></el-tree>
          </div>
          <div style="text-align: center">
            <el-input
              placeholder="输入条码后按回车"
              v-model="queryParams.commodityCode"
              size="small"
              clearable
              style="width: 85%"
              @keyup.enter.native="inputCarriageReturn()"
            >
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>
          </div>
        </div>
        <div></div>
        <el-table :data="gridData" border height="400">
          <el-table-column type="index" label="序号"></el-table-column>
          <el-table-column
            property="commodityName"
            label="商品名称"
            width="100"
          ></el-table-column>
          <el-table-column
            property="barCode"
            label="商品条码"
            width="180"
          ></el-table-column>
          <el-table-column
            property="categoryName"
            label="商品分类"
            width="100"
          ></el-table-column>
          <el-table-column
            property="unit"
            label="单位"
            width="100"
          ></el-table-column>
          <el-table-column property="name" label="入库数量" width="180">
            <template slot-scope="scope">
              <el-input-number
                size="mini"
                :precision="0"
                v-model="scope.row.inventoryQuantity"
                :min="0"
                :max="100000"
                label="请输入"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column
            property="salePrice"
            label="单价"
            width="100"
          ></el-table-column>
          <el-table-column
            property="totalPrice"
            label="总价"
            width="100"
            :formatter="formatterTotalPrice"
          >
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="60">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="deleteProduct(scope.$index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="div-span">
        <span>数量：{{ quantity }} </span><span> 金额：￥{{ amount }}</span>
      </div>
      <div class="div-button">
        <div>
          <el-button
            type="primary"
            size="small"
            @click="save"
            :disabled="saveDisabled"
            >保存</el-button
          >
          <el-button size="small" @click="cancelPutStorage">取消</el-button>
        </div>
      </div>
    </div>
  </el-drawer>
</template>
<script>
import { cloneDeep } from "lodash";
import { getRepository } from "@/api/nonOil/putlntoStorage";
import {
  queryByBarCode,
  warehouseAddList,
  getNonOilCategoryTreeAndCommodity,
} from "@/api/nonOil/putlntoStorage";
export default {
  name: "InventoryEntryNew",
  props: {
    newInventoryEntry: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loadingTree: false,
      saveDisabled: false,
      stationList: [],
      queryParams: { stationId: null, commodityCode: null },
      gridData: [],
      dataTree: [],
      dataTreeId: [],
      defaultProps: {
        children: "children",
        label: "categoryName",
      },
    };
  },
  created() {},
  methods: {
    // 格式化总价
    formatterTotalPrice(row, column) {
      let totalPrice;
      totalPrice = parseFloat(
        (row.inventoryQuantity * row.salePrice).toFixed(10)
      );
      return totalPrice;
    },
    // 点击保存
    save() {
      this.saveDisabled = true;
      this.gridData.forEach((item) => {
        item.totalPrice = item.inventoryQuantity * item.salePrice;
      });
      warehouseAddList(this.gridData)
        .then((res) => {
          if (res.code == 200) {
            this.msgSuccess(res.msg);
            this.$emit("update:newInventoryEntry", false);
          } else {
            this.msgError(es.msg);
          }
          this.saveDisabled = false;
        })
        .catch(() => {
          this.saveDisabled = false;
        });
    },

    // 点击删除
    deleteProduct(index) {
      this.gridData.splice(index, 1);
    },

    // 搜索条形码按回车
    inputCarriageReturn() {
      if (this.queryParams.commodityCode) {
        this.queryParams.commodityCode = this.queryParams.commodityCode.trim();
        queryByBarCode({
          barCode: this.queryParams.commodityCode,
          stationId: this.queryParams.stationId,
        }).then((res) => {
          if (res.data) {
            if (this.gridData.length) {
              let add = 0;
              this.gridData.forEach((item) => {
                if (item.commodityId == res.data.commodityId) {
                  add++;
                }
              });
              if (!add) {
                this.queryParams.commodityCode = null;
                this.gridData.unshift(res.data);
              } else {
                this.$message("商品已添加，请添加其他商品！");
              }
            } else {
              this.gridData.unshift(res.data);
            }
          } else {
            this.$message("未查询到该商品条码");
          }
        });
      }
    },

    // 查询油站
    getStationList() {
      const enterpriseId = this.presentEnterprise?.enterpriseId
        ? this.presentEnterprise.enterpriseId
        : null;
      getRepository({ enterpriseId, status: "1" }).then((res) => {
        this.stationList = res;
        this.queryParams.stationId = this.stationList[0].stationId;
        this.getNonOilCategoryTree();
      });
    },

    // 选择了油站
    changeStationList() {
      this.getNonOilCategoryTree();
      this.gridData = [];
    },

    // 获取树形控件数据
    getNonOilCategoryTree() {
      this.loadingTree = true;
      this.dataTree = [];
      this.dataTreeId = [];
      getNonOilCategoryTreeAndCommodity({
        stationId: this.queryParams.stationId,
      })
        .then((res) => {
          this.loadingTree = false;
          this.dataTree.push(res.data);
          this.unfoldTree(this.dataTree);
        })
        .catch(() => {
          this.loadingTree = false;
        });
    },

    // 数据展开
    unfoldTree(dataTree) {
      dataTree.forEach((item) => {
        this.dataTreeId.push(item.categoryId);
        if (item.children) {
          item.children.forEach((itema) => {
            this.dataTreeId.push(itema.categoryId);
            if (itema.children) {
              itema.children.forEach((itemb) => {
                this.dataTreeId.push(itemb.categoryId);
                if (itemb.children) {
                  itemb.children.forEach((itemc) => {
                    this.dataTreeId.push(itemc.categoryId);
                  });
                }
              });
            }
          });
        }
      });
    },

    // 点击取消入库
    cancelPutStorage() {
      this.$emit("update:newInventoryEntry", false);
    },

    // 关闭入库
    handleClose(done) {
      this.$emit("update:newInventoryEntry", false);
      done();
    },

    // 点击树形控件内容
    handleNodeClick(data) {
      const result = cloneDeep(data);
      if (result.commodity) {
        if (this.gridData.length) {
          let add = 0;
          this.gridData.forEach((item) => {
            if (item.commodityId == result.commodity.commodityId) {
              add++;
            }
          });
          if (!add) {
            this.gridData.unshift(result.commodity);
          } else {
            this.$message("商品已添加，请添加其他商品！");
          }
        } else {
          this.gridData.unshift(result.commodity);
        }
      }
    },
  },
  watch: {
    newInventoryEntry: {
      deep: true, // 深度监听
      handler(newVal, oldVal) {
        if (newVal) {
          this.getStationList();
          this.gridData = [];
          this.queryParams.commodityCode = null;
        }
      },
    },
  },
  computed: {
    quantity() {
      let wadake = 0;
      if (this.gridData.length) {
        this.gridData.forEach((item) => {
          wadake = wadake + item.inventoryQuantity;
        });
      }
      return wadake;
    },
    amount() {
      let wadake = 0;
      if (this.gridData.length) {
        this.gridData.forEach((item) => {
          wadake =
            wadake +
            parseFloat((item.inventoryQuantity * item.salePrice).toFixed(10));
          wadake = parseFloat(wadake.toFixed(3));
        });
      }
      return wadake;
    },
  },
};
</script>
<style scoped lang="scss">
.drawer-div {
  height: 40px;
  line-height: 40px;
  padding-left: 10px;
  background-color: #f1f1f1;
  display: flex;
  margin-bottom: 30px;

  span {
    width: 120px;
  }
}

.div-span {
  height: 40px;
  line-height: 40px;
  background-color: #f1f1f1;
  display: flex;
  justify-content: space-evenly;
  margin-top: 30px;
}

.div-button {
  display: flex;
  justify-content: space-evenly;
  margin-top: 30px;
}

.drawer-tree {
  width: 100%;
}

.drawer-data {
  display: flex;
}

.drawer-tree-input {
  width: 100%;
  height: 368px;
  overflow-y: scroll;
}
</style>
